package com.ccp.dev.form.service;

import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.Dom4jUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.form.dao.SysScriptDao;
import com.ccp.dev.form.model.SysScript;
import com.ccp.dev.form.xml.util.XmlUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

/**
 * 脚本管理 service类
 *
 * @author zhaowj
 */
@Service
public class SysScriptService extends BaseService<SysScript> {

    @Resource
    SysScriptDao sysScriptDao;


    /**
     * 查询全部数据源信息
     *
     * @return 数据源集合
     */
    public List<SysScript> queryListALL() {

        return sysScriptDao.queryListALL();
    }

    /**
     * 查询全部数据源信息
     *
     * @param queryFilter
     * @return 数据源集合
     */
    public List<SysScript> queryListALL(QueryFilter queryFilter) {

        return sysScriptDao.queryListALL(queryFilter);
    }

    /**
     * 返回所有脚本的分类
     *
     * @return
     */
    public List<String> getDistinctCategory() {
        return sysScriptDao.getDistinctCategory();
    }

    /**
     * 根据脚本名称查询脚本
     *
     * @return
     */
    public List<SysScript> getByName(String name) {
        return sysScriptDao.getByName(name);
    }

    /**
     * 删除脚本
     */
    @Transactional(rollbackFor = Exception.class)
    public void delByIds(String[] lAryId) {
        if (BeanUtils.isNotEmpty(lAryId)) {
            for (String id : lAryId) {
                sysScriptDao.delById(id);
            }
        }
    }

    /**
     * 导出自定义表XML
     *
     * @param lAryId
     * @return
     */
    public String exportXml(String[] lAryId) {
        String strXml = null;
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("List");
        for (String id : lAryId) {
            SysScript sysScript = sysScriptDao.getById(id);
            if (BeanUtils.isNotEmpty(sysScript)) {
                // 生成主表
                exportTable(sysScript, root, "Script");
            }
        }
        strXml = doc.asXML();
        return strXml;
    }

    /**
     * 导出全部自定义表XML
     * @param list
     * @return
     */
    public String exportXml(List<SysScript> list) {
        String strXml=null;
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("List");
        for (SysScript sysScript : list) {
            if (BeanUtils.isNotEmpty(sysScript)) {
                // 生成主表
                exportTable(sysScript, root, "Script");
            }
        }
        strXml = doc.asXML();
        return strXml;
    }
    /**
     * 生成表代码
     *
     * @param root
     * @param nodeName
     */
    private void exportTable(SysScript sysScript, Element root, String nodeName) {
        Element elScript = root.addElement(nodeName);

        if (StringUtil.isNotEmpty(sysScript.getName())) {
            elScript.addElement("name").addText(sysScript.getName());
        }
        if (StringUtil.isNotEmpty(sysScript.getScript())) {
            Element elContent = elScript.addElement("content");
            elContent.addCDATA(sysScript.getScript());
        }
        if (BeanUtils.isNotEmpty(sysScript.getCategory())) {
            elScript.addElement("type").addText(sysScript.getCategory());
        }
        if (BeanUtils.isNotEmpty(sysScript.getMemo())) {
            elScript.addElement("Memo").addText(sysScript.getMemo());
        }
    }

    /**
     * 导入自定义脚本XML
     *
     * @param inputStream 输入流
     * @throws Exception 可能解析xml失败
     */
    public void importXml(InputStream inputStream) throws Exception {
        Document doc = Dom4jUtil.loadXml(inputStream);
        Element root = doc.getRootElement();
        List<Element> itemLists = root.elements();
        if (BeanUtils.isNotEmpty(itemLists)) {
            for (Element elm : itemLists) {
                String itemName = elm.element("name").getText();
                if(this.checkRepeatName(null,itemName)) {
                    String scriptText = elm.element("content") == null ? "" : elm.element("content").getText();
                    String memoText = elm.element("Memo") == null ? "" : elm.element("Memo").getText();
                    String scriptType = elm.element("type").getText();
                    SysScript sysScript = new SysScript();
                    sysScript.setId(UUIDUtils.getUUIDFor32());
                    sysScript.setName(itemName);
                    sysScript.setScript(scriptText);
                    sysScript.setMemo(memoText);
                    sysScript.setCategory(scriptType);
                    sysScriptDao.add(sysScript);
                }else {
                    throw new RuntimeException("‘" + itemName + "’脚本已经存在，请检查你的xml文件！");
                }
            }
        }
    }

    /**
     * 脚本名称校验唯一性
     * @param id            只作用于编辑保存时过滤原数据
     * @param scriptName    脚本名称
     * @return              ==ture，名称可用；==false，名称已存在不可用
     */
    public boolean checkRepeatName(String id, String scriptName) {
        return sysScriptDao.checkRepeatName(id,scriptName) == 0;
    }
}
